package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.model.user.UserVO
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.FlowUseCase
import com.ccteam.shared.result.BaseItemData
import com.ccteam.shared.result.user.MeHomeInfoItem
import com.ccteam.shared.result.user.MeHomeNotLoginItem
import com.ccteam.shared.utils.EMPTY_STRING
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/19
 *
 * 首页用户信息获取
 */
class MeHomeDataUseCase @Inject constructor(
    private val userRepository: UserRepository,
    private val userCore: UserCore
): FlowUseCase<Nothing?, List<BaseItemData>>(
    Dispatchers.IO
) {
    override fun execute(parameters: Nothing?): Flow<Resource<List<BaseItemData>>> {
        val isLogin = userCore.isLogin.value
        val userId = userCore.userInfo.value.userId

        if(!isLogin){
            return flowOf(Resource.Success(generateNotLoginList()))
        }
        return userRepository.getUserInfo(userId).map {
            when (it) {
                is Resource.Success -> {
                    Resource.Success(transformToUserInfo(it.data ?: emptyList()))
                }
                is Resource.Loading -> {
                    Resource.Loading(null)
                }
                else -> {
                    Resource.Error(it.errorCode,it.message ?: "未知错误",null)
                }
            }
        }

    }

    private fun generateNotLoginList(): List<BaseItemData>{
        return listOf(MeHomeNotLoginItem())
    }

    private fun transformToUserInfo(listUserVo: List<UserVO>): List<BaseItemData>{
        if(!listUserVo.isNullOrEmpty()){
            return listOf(
                MeHomeInfoItem(listUserVo[0].id,listUserVo[0].name,
                listUserVo[0].introduction ?: EMPTY_STRING,listUserVo[0].photoUrl ?: EMPTY_STRING,listUserVo[0].playlistNum,listUserVo[0].momentNum)
            )
        }
        return emptyList()
    }
}